﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DiaosFix.Core
{
    public class UserCardOperator
    {
        private DiaosFixEntities context = new DiaosFixEntities();

        public int GetCardNumberByUser(Users u)
        {
            return this.GetCardNumberByUser(u.Id);
        }

        public int GetCardNumberByUser(int userId)
        {
            var user = context.UserCard.Where(p => p.UserId == userId).SingleOrDefault();
            if (null != user)
            {
                return user.CardNumber;
            }
            return 0;
        }

        public int SendGoodmanCardTo(Users u)
        {
            return this.SendGoodmanCardTo(u.Id);
        }

        public int SendGoodmanCardTo(int userId)
        {
            var user = context.Users.Where(p => p.Id == userId).SingleOrDefault();
            if (null != user)
            {
                if (user.IsInRole(PubConstant.UserTypes.Diaos))
                {
                    return context.SendGoodmanCardTo(userId);
                }
            }
            return 0;
        }

        public Response<object> ClearGoodmanCardOf(Users u)
        {
            Response<object> response = new Response<object>();

            if (u.UserType.Name == "Diaos")
            {
                var obj = context.UserCard.Where(p => p.UserId == u.Id).SingleOrDefault();
                if (null != obj)
                {
                    obj.CardNumber = 0;
                    if (context.SaveChanges() > 0)
                    {
                        response.IsSuccess = true;
                        response.Message = string.Empty;
                        response.Item = null;
                    }
                    else
                    {
                        response.IsSuccess = false;
                        response.Message = "Error saving changes to database";
                        response.Item = null;
                    }
                }
                else
                {
                    response.IsSuccess = false;
                    response.Message = "There's no record for the specific user";
                    response.Item = null;
                }
            }
            else
            {
                response.IsSuccess = false;
                response.Message = "Cannot clear goodman card for non-diaos user";
                response.Item = null;
            }

            return response;
        }
    }
}
